package com.lw.leetcode.binary;

import com.lw.leetcode.node.LeafSimilar;

import java.util.Arrays;

/**1170. 比较字符串最小字母出现频次
 * @Author liw
 * @Date 2021/5/24 10:45
 * @Version 1.0
 */
public class NumSmallerByFrequency {

    public static void main(String[] args) {
        NumSmallerByFrequency test = new NumSmallerByFrequency();
        String[] a = {"b","cc"};
        String[] b = {"a","aa","aaa","aaaa"};
        int[] ints = test.numSmallerByFrequency(a, b);
        System.out.println(Arrays.toString(ints));
    }


    public int[] numSmallerByFrequency(String[] queries, String[] words) {

        int b = words.length;
        int[] w = new int[b];
        int[] buckets = new int[26];
        for (int i = 0; i < b; i++) {
            w[i] = count(words[i], buckets);
        }
        Arrays.sort(w);
        int a = queries.length;
        int[] values = new int[a];
        for (int i = 0; i < a; i++) {
            values[i] = getIndex(w, count(queries[i], buckets), 0, b - 1);
        }
        return values;
    }

    private int getIndex(int[] arr, int t, int st, int end) {
        if (arr[end] <= t) {
            return 0;
        }
        if (arr[st] > t) {
            return end + 1;
        }
        int e = end + 1;
        while (st < end) {
            int m = st + ((end - st) >> 1);
            if (arr[m] > t) {
                end = m;
            } else {
                st = m + 1;
            }
        }
        return e - st;
    }

    private int count(String a, int[] buckets) {
        Arrays.fill(buckets, 0);
        for(int i = 0, length = a.length(); i < length; i++) {
            buckets[a.charAt(i) - 'a']++;
        }
        int j;
        for(j = 0; j < 26;j++) {
            if(buckets[j] != 0) {
                return buckets[j];
            }
        }
        return 0;
    }

}
